package com.bruce.tool.logger.rabbit.converter;

import com.alibaba.fastjson.JSON;
import com.bruce.tool.logger.rabbit.aop.SpringAopXmlLogger;
import com.bruce.tool.logger.rabbit.aop.SpringAspectLogger;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.SimpleMessageConverter;

import java.io.UnsupportedEncodingException;

public class FastJsonMessageConverter extends SimpleMessageConverter {

    private static Logger logger = LoggerFactory.getLogger(SpringAspectLogger.class);

    @Override
    protected Message createMessage(Object object, MessageProperties messageProperties) {
        String jsonStr = JSON.toJSONString(object);
        byte[] bytes = null;
        try {
            bytes = jsonStr.getBytes(DEFAULT_CHARSET);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        messageProperties.setContentEncoding(DEFAULT_CHARSET);
        if (bytes != null) {
            messageProperties.setContentLength(bytes.length);
        }
        String messageId = messageProperties.getMessageId();
        if(StringUtils.isBlank(messageId)){
            messageId = SpringAspectLogger.MESSAGE_THREADLOCAL.get();
            if(StringUtils.isNotBlank(messageId)){
                SpringAspectLogger.MESSAGE_THREADLOCAL.remove();
            }else {
                messageId = SpringAopXmlLogger.MESSAGE_THREADLOCAL.get();
                if (StringUtils.isNotBlank(messageId)) {
                    SpringAopXmlLogger.MESSAGE_THREADLOCAL.remove();
                }
            }
        }
        messageProperties.setMessageId(messageId);
        return new Message(bytes, messageProperties);
    }

}
